package com.ning.logging.aspect;

import com.ning.common.util.JwtUtil;
import com.ning.logging.service.LogService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import com.ning.user.bean.Log;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Map;

@Aspect
@Component
public class LogAspect {
    @Autowired
    private LogService logService;
    // 切入点
    @Pointcut("execution(* com.ning..web.controller.*.*(..)) && @annotation(com.ning.logging.anno.LoggingAccess)")
    public void pointcut(){}



    // 环绕通知
    @Around("pointcut()")
    public Object around(ProceedingJoinPoint pjp){


        System.out.println("LogAspect.around");
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
        String token = request.getHeader("Authorization");
        Map<String, Object> info = JwtUtil.getInfo(token);
        Log log = Log.builder()
                .logUsername((String) info.get("username"))
                .logRealname((String) info.get("realname"))
                .logRequestMethod(request.getMethod())
                .logRequestUri(request.getRequestURI())
                .logTime(new Date())
                .build();


        try {
            // 增强目标方法
            logService.addLog(log);
            // 目标方法执行
            return pjp.proceed(pjp.getArgs());
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        return null;
    }
}
